<?php
namespace App\Models\Account;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Support\Facades\Request;
use App\Admin\Extra\Search\Html;
use \Illuminate\Support\Facades\Input;

class Behavior extends  Model{

	protected $table='behavior_log';
    protected $_db_select = 'remote_bgsi';

    public $_max_count = 0;
    const DB_FIELDS = 'imei,player_id,op_module,op,op_val_1,op_val_2,op_val_3,level,diamond,m_model,op_time';

    public function __construct()
    {
        \App\Models\Area::RemoteBgsiSelectByArea(Request::get('area'));
    }

	public function paginate()
    {
    	$perPage = Request::get('per_page', 20);

        $page = Request::get('page', 1);

        $start = ($page-1)*$perPage;

        //$data = \DB::connection($this->selectdb())->table($tableAccount)->skip($page* $perPage)->take($perPage)->get();
        //$data = $data->toArray();
        $rw = \DB::connection($this->selectdb())->table($this->table)->select('id', \DB::raw(self::DB_FIELDS));
        self::SourceCondition($rw);
        $total = $rw->count();
        $rw->orderBy('op_time', "DESC");
        $rw->skip($start)->take($perPage);
        $data =  $rw->get();
        $data = $data->toArray();

        \Log::debug(__METHOD__, [$rw->toSql()]);
        // $data = json_decode($data, true);
        self::attachItemWithOpAlias($data);
        self::attachWithItemAlias($data);
        $list = static::hydrate($data);

        $paginator = new LengthAwarePaginator($list, $total, $perPage);

        $paginator->setPath(url()->current());

        return $paginator;
    }

    public static function with($relations)
    {
        return new static;
    }


    public function selectdb($select = ''){
        if ($select) {
            return $this->_db_select = $select;
        }
        return $this->_db_select;
    }

    public function getConnectionName(){
        return $this->selectdb();
    }
    public function getTable($table = ''){
    
        if ($table) {

            $this->table = $table;
        }

        return $this->table;
    }
    public static function SourceCondition(&$rw)
    {
        $cond = Request::all();

        if ($cond['player_id']){
            $pids = explode(',', $cond['player_id']);
            $rw->whereIn("player_id", $pids);
        }
        if ($cond['op']){
            $rw->where("op", $cond['op']);
        }
        // \Log::debug('[PLAYER][BEHAVIOR][COND]', [$cond['op_module']]);
        if ($cond['op_module']){
            if (is_array($cond['op_module'])) {
                $rw->whereIn("op_module", $cond['op_module']);
            } else {
                $rw->where("op_module", $cond['op_module']);
            }
        }
        // if ($cond['area']){
        //     $rw->where("area", $cond['area']);
        // }
        if ($cond['ops']) {
            $rw->whereIn("op", $cond['ops']);
        }

        if (is_array($cond['op_time'])) {
            $start = \App\ModelStatistic\StatisticCommon::GetIntTime($cond['op_time']['start']) ?: 0;
            $rw->where("op_time", ">", $start);
            $end = \App\ModelStatistic\StatisticCommon::GetIntTime($cond['op_time']['end']) ?: 0;
            if ($end) {
                $rw->where("op_time", "<", $end);
            }
        }
    }



    public static function attachItemWithOpAlias(&$list) {
        $op_alias_arr = self::getOpAlias();
        $op_m_alias_arr = self::getOpmoduleAlias();
        // \Log::debug("attachItemWithOpAlias", [$op_m_alias_arr]);
        foreach ($list as &$obj) {
            $alias = $op_alias_arr[$obj->op] ?: $op_alias_arr[$obj->op_module . $obj->op];
            
            $obj->op_alias = $alias;
            $arr_m_alias = explode('.', $obj->op_module);
            $obj->op_m_alias = $op_m_alias_arr[$obj->op_module]?:($op_m_alias_arr[$arr_m_alias[0].'.'.$arr_m_alias[1]]);
        }
        return $list;
    }

    public static function attachWithItemAlias(&$list) {
        $item_model = New \App\Models\Item\Item();
        $item_alias_arr = $item_model->GetItemArray(0, true);
        foreach ($list as &$obj) {
            $alias = $item_alias_arr[$obj->op_val_1]?:$item_alias_arr[$obj->op_val_2];
            
            $alias && $obj->item_alias = $alias['name'];
            
        }
        return $list;
    }

    public static function getCoinButtons($req) {
        $ops_labels = [
            'S.DIAMOND_REDUCE' => '钻石--',
            'S.DIAMOND_ADD' => '钻石++',
            'S.TICKET_REDUCE' => '红钻--',
            'S.TICKET_ADD' => '红钻++',
            'S.GOLD_REDUCE' => '金币--',
            'S.GOLD_ADD' => '金币++',
            'S.ITEM_ACCEPT' => '物品获得',
            'S.ITEM_TOKEN' => '物品扣除',
        ];
        $ops = $req['ops'] ?:[];
        
        $exist_func = function($op_one)use($ops) {
            foreach ($ops as $val) {
                if ($val == $op_one) {
                    return true;
                }
            }
            return false;
        };
        $param_arr= $req ?:[];
        $show_button = function($op_one)use($ops, $exist_func, $param_arr, $ops_labels){
            if ($exist_func ($op_one)) {
                $param_arr['ops'] = self::changeCoinButtonData($ops, $op_one, 0);
                return Html::button( $ops_labels[$op_one], \App\Service\Common::build_url_query(url()->current(),  $param_arr), 'btn-goto btn-warning');
            }
            $param_arr['ops'] = self::changeCoinButtonData($ops, $op_one, 1);
            return Html::button( $ops_labels[$op_one], \App\Service\Common::build_url_query(url()->current(),  $param_arr), 'btn-goto btn-info');
        };

        if (empty($ops)) {
            $ops = array_keys(($ops_labels));
        }
        $latest_btn = [];
        foreach ($ops_labels as $key=>$babel) {
            $latest_btn[] = $show_button($key);
        }
        return $latest_btn;
    }

    public static function changeCoinButtonData($ops, $op_one, $op_sign) {
        // 加上查询操作到
        if ($op_sign == 1) {
            foreach ($ops as $val) {
                if ($val == $op_one) {
                    return $ops;
                }
            }
            $ops[] = $op_one;
            return $ops;
        }
        foreach ($ops as $key => $val) {
            if ($val == $op_one) {
                unset($ops[$key]);
            }
        }
        return $ops;
    }
    public static function getOpAlias() {
        return [
            'OpenGame'      => '打开游戏',
            'Backstage'     => '后台挂起',
            'CloseGame'     => '关闭游戏',
            'First_LoadingGame'     => '第一次加载游戏',
            'End_First_LoadingGame'     => '第一次加载游戏完成',
            'StartLoadingGame'     => '开始加载游戏',
            'EndLoading'     => '游戏加载完毕',
            'AchieveRegist_Success'     => '点击完成注册 - 成功提交',
            'AchieveRegist_NoneAccount'     => '点击完成注册 - 帐号长度不足',
            'AchieveRegist_NonePassword'     => '密码长度不足',
            'AchieveRegist_FormatError'     => '帐号与密码相同',
            'AchieveRegister_Success'     => '注册成功',
            'AchieveRegister_AccountIllegal'     => '帐号冲突',
            'LoginBtn_NoneAccountNPassword'     => '点击登录按钮 - 未输入帐号密码',
            'AchieveLogin_Success'     => '成功登录',
            'CheckSkillBtn'     => '查看技能按钮',
            'CutSelectRoleBtn'     => '点击切换选择英雄',
            'RandomNameBtn'     => '点击随机名字',
            'NameInputCli'     => '点击名字输入框',
            'CreateRoleBtn'     => '创建角色',
            'GetTask_Guidance_ClickMission'     => '点击领取任务（引导）- 成功点击任务',
            'GetTask_Guidance_ClickOther'     => '点击领取任务（引导）- 点击界面其他位置',
            'GetTask_Guidance_ClickNPC'     => '点击领取任务（引导）- 点击NPC领取',
            'GetTask_Finding'     => '点击领取任务（寻路）',
            'InTask_Skip'     => '点击交任务 - 跳过',
            'GetTask_Reward'     => '点击领取任务奖励',
            'Complete_GatherTask'     => '完成采集任务',
            'OnLineRewardBtn_Gain'     => '在线奖励按钮 - 可以领取',
            'OnLineRewardBtn_CantGain'     => '在线奖励按钮 - 不可领取',
            'GetOnLineRewardBtn_ClickGainBtn'     => '获取在线奖励按钮 - 点击领取',
            'GetOnLineRewardBtn_Close'     => '获取在线奖励按钮 - 点击界面其他位置',
            'FirstChargeBtn'     => '首充按钮',
            'ChargeBtn'     => '充值按钮',
            'SovereignWelfareBtn'     => '至尊福利',
            'StoreBtn'     => '商城',
            'AltarBtn'     => '祭坛',
            'EquipBtn'     => '装备',
            'HeroBtn'     => '英雄',
            'AdventureBtn'     => '冒险按钮',
            'FirstChargeBtn_GotoCharge'     => '首充按钮 - 前往充值',
            'FirstChargeBtn_Close'     => '首充界面 - 关闭',
            'Level_CutHero'     => '关卡战斗内点击切换英雄',
            'Level_ReleaseSummonCli'     => '关卡战斗内点击释放召唤技',
            'IntensifyCli'     => '变强界面点击',
            'AltarCli'     => '祭坛界面点击',
            'EquipCli'     => '装备界面点击',
            'EquipTabCli_SwitchToEquip'     => '装备界面装备页签点击 - 切换选中的装备',
            'EquipTabCli_IntensifyOnce'     => '装备界面装备页签点击 - 强化一次',
            'EquipTabCli_IntensifyAll'     => '装备界面装备页签点击 - 一键强化',
            'EquipTabCli_TabChangeEqiup'     => '装备界面装备页签点击 - 换装子页签',
            'EquipTabCli_TabIntensify'     => '装备界面装备页签点击 - 强化子页签',
            'EquipTabCli_EquipRecommend'     => '装备界面装备页签点击 - 推荐-装备按键',
            'EquipTabCli_EquipPutOn'     => '装备界面装备页签点击 - 推荐-获取按键',
            'HeroCli_SwitchTab'     => '英雄界面点击 - 切换分页',
            'HeroCli_SummonHero'     => '英雄界面点击 - 点击英雄召唤',
            'HeroCli_SwitchHero'     => '英雄界面点击 - 点击英雄切换',
            'HeroCli_Close'     => '英雄界面点击 - 返回',
            'Guide_AchieveMove'     => '完成移动教学',
            'Guide_AchieveSkill'     => '完成技能教学',
            'Guide_AchieveElite'     => '完成精英战斗',
            'Guide_AchieveBoss'     => '完成BOSS战斗',
            'MainWait_InputUser'     => '显示主界面等待输入账号',
            'InputUserCli'     => '点击账号输入框',
            'OneRegisterBtn'     => '点击一秒注册按钮',
            'VisitorLoginBtn'     => '点击游客登录按钮',
            'InputPasswordCli'     => '点击密码输入框',
            'RegisterBackBtn'     => '点击注册返回按钮',
            'Register_UserInputCli'     => '点击注册界面账号输入框',
            'LoginBtn'     => '点击登录按钮',
            'AchieveLogin'     => '完成登录',
            'OpenNoticeBtn'     => '点击打开公告',
            'NoticePanel'     => '点击公告界面',
            'CutAccountBtn'     => '点击切换账号',
            'CutServeBtn'     => '点击切换服务器',
            'SelectServeBtn'     => '选择服务器',
            'StartGameBtn'     => '点击开始游戏',
            'EntryLoading'     => '进入加载',
            'AchieveLoading'     => '完成加载',
            'MainCityBtn'     => '主界面按钮',
            'Level_LevelBtn'     => '点击关卡界面关卡',
            'Level_EmbattleCli'     => '点击关卡布阵界面',
            'EmbattleCli'     => '点击布阵界面',
            'Level_LevelPlotCli'     => '点击关卡战斗内剧情',
            'CombatBtn'     => '点击战斗内按钮',
            'Level_PauseCli'     => '关卡战斗内暂停界面点击',
            'Level_EntryCombat'     => '关卡战斗内进入战斗',
            'Level_OverCombat'     => '关卡战斗内脱离战斗',
            'Level_Move'     => '关卡战斗内移动',
            'Level_Overtime'     => '关卡战斗内超时失败',
            'Level_PassCli'     => '关卡结算界面点击关卡过关',
            'DrawCard_ResultCli'     => '抽卡结果界面点击',
            'RoleIconCli'     => '主界面点击头像',
            'RoleSettingCli'     => '主角设置点击切换英雄',
            'RecommendationLetter'     => '任务点击推荐信',
            'EntryAthletics	'     => '进入竞技场',
            'Basic'     => '打开游戏',

            // 服务器操作指令
            'S.DIAMOND_ADD'     => '钻石++',
            'S.DIAMOND_REDUCE'     => '钻石--',
            'S.GOLD_ADD'     => '金币++',
            'S.GOLD_REDUCE'     => '金币--',
            'S.GUILD_COIN_REDUCE'     => '公会币消耗',
            'S.GUILD_COIN_ADD'     => '公会币增加',
            'S.PVE_COIN_REDUCE'     => '远征货币消耗',
            'S.PVE_COIN_ADD'     => '远征货币增加',
            'S.THRONE_COIN_REDUCE'     => '永夜王座币',
            'S.ARENA_COIN_REDUCE'     => '竞技币',
            'S.ACCEPT'     => '接受任务',
            'S.COMPLETE'     => '完成任务',
            'S.ADD'     => '英雄添加',
            'S.LEVEL_UP'     => '等级增加',
            'S.STAR_UP'     => '英雄升星',
            'S.GRADE_UP'     => '英雄突破',
            'S.PLAYER_LEVEL_UP'     => '战队升级',
            'S.START'     => '战斗开始',
            'S.FIGHT_FAIL'     => '战斗结算失败	',
            'S.FIGHT_SUCCESS'     => '战斗结算成功',
            'S.CREATE'     => '创建公会',
            'S.DISBAND'     => '解散公会',
            'S.JOIN'     => '加入公会',
            'S.LOTTERY'     => '抽奖',
            'S.SOUL_EXCHANGE'     => '魂石置换',
            'S.login'     => 'server完成登录',
            'S.logout'     => '登出',
            'S.REGISTER'   => '注册',
            'S.draw_purple'   => '钻石抽奖',
            'S.use'     => '使用物品',
            'S.leve_reward' => '领取成就',
            'S.CARNIVAL_DETAIL'     => '嘉年华领奖',
            'S.CARNIVAL_DAY' => '嘉年华购买折扣',
            'S.draw_blue' => '金币抽',
            'S.REFRESH_SOUL' => '刷新魂匣魂石',
            'S.REFRESH_SOUL_HERO' => '刷新魂匣英雄',
            'S.refresh_times' => '刷新次数',
            'S.ASSESSMENT_DETAIL' => '目标奖励领取',
            'S.HORN' => '钻石聊天',
            'S.buy_thew' => '购买体力',
            'S.buy_item' => '购买物品',
            'S.FIGHT' => '副本战斗',
            'S.flash' => '副本扫荡',
            'S.BOX_REWARD' => '副本箱子奖励',
            'S.debris_compose' => '碎片合成',
            'S.growth_fund' => '购买成长基金',
            'S.level_buy' => '等级购买',
           
            'S.forever_card' => '购买永久卡',

            'S.shopS.buy' => '黑市购买',
            'S.noob_66' => '66连抽',
            'S.WORLD_BOSSS.FIGHT' => '世界boss战斗',
            'S.TICKET_ADD' => '红钻++',
            'S.TICKET_REDUCE' => '红钻--',
            'S.BATCH_DISTILL' => '批量领取邮件',
            'S.ARENA_COIN_ADD' => '得角斗场币',
            'S.BUY' => '购买',
            'S.RUNE_COIN_ADD' => '符文碎片++',
            'S.RUNE_COIN_REDUCE' => '符文碎片--',
            'S.BUY_DIAMOND_DRAW' => '购买中级抽奖券',
            'S.PVP_COIN_ADD' => 'PVP币++',
            'S.PVP_COIN_REDUCE' => 'PVP币--',
            'S.LEVEL_REWARD' => '等级奖励',
            'S.LOGIN' => '登录',
            'S.wear_equip' => '穿戴装备',
            'S.ENTER' => '进入',
            'S.REWARD' => '获得奖励',
            'S.new_player_7' => '新手7日领奖',
            'S.cond_reward' => '条件礼包领奖',
            'S.THRONE_COIN_ADD' => '永夜王座币++',
            'S.THRONE_FIRST_FIGHT' => '永夜王座首次战斗',
            'S.preferential' => '日周月礼包',
            'S.online' => '在线',

            // 以下新版本中 可以不用有了
            'S.extreme.single_supper' => '至尊双倍钻石',
            'S.ACTIVITY.GROWTH_FOUND_BUY' => '成长基金',
            'S.ACTIVITY.FOUND_WEEK' => '突破基金',
            'S.ITEM_ACCEPT' => '物品获得',
            'S.ITEM_TOKEN' => '物品扣除',
        ];
    }

    public static function getOpmoduleAlias() {
        return [
            'S.recharge.preferential' => '日周月+新手',
            'S.recharge.second_charge' => '续充',
            'S.ALTAR.REFRESH_SOUL_HERO' => '刷新魂匣',
            'S.UNLOCK_PREV.REWARD' => '功能预开启',
            'S.PET' => '宠物',
            'S.rune.sell' => '出售符文',
            'S.rune' => '符文',
            'S..VIP.LEVEL_REWARD' => 'VIP等级奖励',
            'S.rune.unlock' => '符文解锁',
            'S.mission.offer_reward' => '悬赏任务',
            'S.pve_moba.draw_reward' => '竞技场胜利抽奖',
            'S.mission.refresh' => '任务刷新',
            'S.common.buy_item' => '购买物品',
            'S.common.buy_thew' => '购买体力',
            'S.ALTAR.REFRESH_HERO' => '祭坛刷新英雄',
            'S.guild.donation' => '=公会钻石捐献',
            'S.lucky_draw.draw' => '点金手',
            'S.mall.buy' => '商城购买',
            'S.ALTAR.REFRESH_SOUL' => '刷新魂石',
            'S.altar.draw_soul' => '购买魂石抽奖券',
            'S.CHAT.horn' => '聊天小喇叭',
            'S.pet.draw' => '宠物抽奖',
            'S.PLAYER.CHANGE_NAME' => '修改名称',
            'S.guild.create' => '创建公会',
            'S.rune.unlock_page' => '解锁符文页',
            'S.arena.refresh' => '角斗场刷新',
            'S.arena.refresh_times' => '角斗场次数',
            'S.shop.buy' => '黑市购买',
            'S.altar.draw_diamond' => '购买祭坛中级抽奖券',
            'S.GM.add_item' => 'GM 添加红钻',
            'S.recharge.ticket' => '充值红钻',
            'S.guild.red_pack' => '公会红包',
            'S.extreme.growth_fund' => '成长基金',
            'S.dungeon_activity_secret.30124' => '神秘宝藏',
            'S.dungeon_activity_secret.30123' => '神秘宝藏',
            'S.dungeon_activity_secret' => '神秘宝藏',
            'S.WORLD_BOSS' => '世界boss',
            'S.WORLD_BOSS.FIGHT' => '世界boss结算',
            'S.pve_moba_draw_reward.' => '竞技场胜利抽奖',
            'S.dungeon_activity_endless' => '无尽试练',
            'S.MAIL' => '邮件',
            'S.MISSION' => '任务',
            'S.mission.daily' => '日常任务',
            'S.mission.trunk' => '主线任务',
            'S.mission.offer' => '悬赏任务',
            'S.mission.rewards' => '任务奖励',
            'S.dungeon' => '冒险副本',
            'S.extreme' => '至尊福利',
            'S.recharge.month_card' => '月卡',
            'S.recharge.forever_card' => '终身卡',
            'S.ACTIVITY.CARNIVAL_DETAIL' => '嘉年华',
            'S.ACTIVITY.GROWTH_FOUND_BUY' => '成长基金',
            'S.ACTIVITY.FOUND_WEEK' => '突破基金',
            'S.ACTIVITY.LEVEL_BUY' => '等级购买',
            'S.ACTIVITY.HERO_CHARGE_BUY' => '英雄礼包',
            'S.welfare' => '福利',
            'S.item' => '物品',
            'S.shop' => '黑市',
            'S.mall' => '商城',
            'S.GUILD' => '公会',
            'S.expedition' => '远征',
            'S.recharge' => '充值',
            'S.EQUIP' => '装备',
            'S.EQUIPMENT' => '装备',
            'S.HERO' => '英雄',
            'S.VIP' => 'VIP',
            'S.ARENA' => '角斗场',
            'S.arena' => '角斗场',
            'S.LOGIN' => '登录模块',
            'S.achievement' => '成就',
            'S.item.sell' => '背包出售',
            'S.DUNGEON_ACTIVITY' => '活动副本',
            'S.ACTIVITY.ASSESSMENT_DETAIL' => '目标考核',
            'S.lucky_draw' => '点金手',
            'S.pve_moba' => '竞技场',
            'S.reset_elite_dungeon' => '重置精英副本',
            'S.recharge.cond_reward' => '限时礼包',
            'S.single_supper' => '超值单冲',
            'S.activity.first_charge' => '首冲',
            'S.activity.second_charge' => '续充',
            'S.extreme.single_supper' => '至尊双倍钻石',
            'S.extreme.total_cost' => '累计花费',
            'S.extreme.total_charge' => '累计充值',
            'S.extreme.everyday' => '每日充值',
            'S.recharge.month_card' => '月卡',
            'S.recharge.forever_card' => '终身卡',
            'S.welfare.new_player_7' => '福利7日登陆',
            'S.welfare.level' => '福利等级',
            'S.welfare.sign' => '签到',
            'S.welfare.online' => '福利在线',
            'S.PLAYER.PLAYER_LEVEL_UP' => '战队升级',
            'S.ALTAR.LOTTERY' => '祭坛抽奖',
            'S.item.use' => '物品使用',
            'S.RECHARGE_BASE' => '充值购买',
            'S.xxxxxxx' => 'xxxxxx',
        ];
    }
}
